package net.cctms.zhishu.webAppFramework.manager;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;


import net.cctms.zhishu.webAppFramework.utils.Log;


/**
 * APP后台service
 */
public class AppService extends Service {
    private static final long KEEP_ALIVE_INTERVAL = 1000 * 60 * 20; //20分钟
    private static final String TAG = AppService.class.getSimpleName();
    private String lastClipText = "";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private Handler mHandler = new Handler();
    @Override
    public void onCreate() {
        super.onCreate();
        //registerClipboardListener();
        startKeepAlives();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "output time : " + System.currentTimeMillis());
        return START_STICKY;
    }

    private void startKeepAlives() {
        stopKeepAlives();// 先取消之前定时器

        Intent intent = new Intent();
        intent.setClass(this, AppService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, intent, 0);
        AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
        //第一个参数AlarmManager.RTC_WAKEUP 修改为 AlarmManager.RTC ，用绝对时间。 modify by xuxd
        alarmMgr.setRepeating(AlarmManager.RTC,
                System.currentTimeMillis() + KEEP_ALIVE_INTERVAL,
                KEEP_ALIVE_INTERVAL, pi);
    }

    private void stopKeepAlives() {
        Intent intent = new Intent();
        intent.setClass(this, AppService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, intent, 0);
        AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmMgr.cancel(pi);
    }


}
